<template>
  <div class="back">
    <div class="login">
      <h3>叩丁狼商品管理系统</h3>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" placeholder="admin">
            <template #prefix>
              <el-icon :size="24"><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            placeholder="请输入密码"
          >
            <template #prefix>
              <el-icon :size="24"><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            v-antisana="1000"
            @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { loginAPI } from "./api";
import { useRouter } from "vue-router";
const router = useRouter();
const ruleFormRef = ref<FormInstance>();

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === "") {
    // 如果校验不通过，人家规定我们要调用 callback，传入一个error对象，把信息传入error对象
    callback(new Error("请输入密码"));
  } else {
    // 校验成功，就直接调用callback就行
    callback();
  }
};

const ruleForm = reactive({
  username: "admin",
  password: "",
});

const rules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ validator: validatePass, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      // valid是true代表数据校验难过，可以发请求
      // 请求
      loginAPI(ruleForm).then((res) => {
        if (res.code == 200) {
          // 登录成功
          // 1.存token
          localStorage.setItem("token", res.data.tokenHead + res.data.token);
          // 2.跳转
          router.push("/index");
          // 3.提示
          ElMessage.success("登录成功");
        }
      });
    } else {
      // 提示用户
      ElMessage.error("请加钱");
      // 记得如果是校验失败，要返回false
      return false;
    }
  });
};
</script>

<style scoped lang="less">
.back {
  width: 100%;
  height: 100%;
  background-color: #2d3a4b;
  overflow: hidden;
}
.login {
  width: 400px;
  margin: 200px auto 0;
  // transform: scale(1.5);
  h3 {
    padding: 20px 0;
    color: #fff;
    text-align: center;
  }
  :deep(.el-input__inner) {
    height: 50px;
  }
  :deep(.el-button--primary) {
    width: 100%;
  }
}
</style>
